﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace CSharpHelpers.Commons
{
    class SandBoxHelper
    {
        private TcpListener m_sandBoxListener;

        public SandBoxHelper(int port)
        {
            IPAddress ipAddress = IPAddress.Any;
            m_sandBoxListener = new TcpListener(ipAddress, port);
        }

        /// <summary>
        /// 處理Web Flash請求
        /// </summary>
        /// <param name="synResult"></param>
        public void ConnectRequest(IAsyncResult synResult)
        {
            try
            {
                Socket socket = m_sandBoxListener.EndAcceptSocket(synResult);
                byte[] buffer = new byte[1024];
                SocketError socketError;
                int len = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None, out socketError);
                string response = "<?xml version=\"1.0\"?><cross-domain-policy><site-control permitted-cross-domain-policies=\"all\"/><allow-access-from domain=\"*\" to-ports=\"*\"/></cross-domain-policy>\0";
                string msg = string.Empty;
                if (socketError == SocketError.Success)
                {
                    msg = Encoding.Default.GetString(buffer, 0, len).TrimEnd('\0');
                    if (msg.Equals("<policy-file-request/>"))
                    {
                        socket.Send(Encoding.Default.GetBytes(response));
                    }
                }
                socket.Close();
                m_sandBoxListener.BeginAcceptSocket(this.ConnectRequest, null);
            }
            catch { }
        }

        /// <summary>
        /// 打開沙箱
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        public bool Start()
        {
            bool bSuccess = false;
            try
            {
                m_sandBoxListener.Start();
                m_sandBoxListener.BeginAcceptSocket(new AsyncCallback(ConnectRequest), null);
                bSuccess = true;
            }
            catch { }
            return bSuccess;
        }

        /// <summary>
        /// 關閉
        /// </summary>
        public void Stop()
        {
            if (m_sandBoxListener != null)
            {
                m_sandBoxListener.Stop();
                m_sandBoxListener = null;
            }
        }
    }
}
